<template>
  <div class="table-page flex-col">
    <div class="round-14 bgfff p-20 flex-col mb-20">
      <div class="flex w-full flex-a-c">
        <a-button type="outline" shape="round">{{ dataInfo.payAccountName }}</a-button>
        <div class="flex flex-a-c font-bold text-size-18 ml-10">{{ dataInfo.name }}</div>
      </div>
      <div class="flex w-full flex-a-c flex-wrap">
        <div class="mt-20" style="width: 33%">
          总用户数：{{ dataInfo.totalCount }}个 总金额：￥{{ dataInfo.totalAmount }}元
        </div>
        <div class="mt-20" style="width: 33%; color: rgba(67, 207, 124, 1)">
          成功用户数：{{ dataInfo.successCount }}个 成功金额：￥{{ dataInfo.successAmount }}元
        </div>
        <div class="mt-20" style="width: 33%; color: rgba(255, 0, 0, 1)">
          失败用户数：{{ dataInfo.failCount }}个 失败金额：￥{{ dataInfo.failAmount }}元
        </div>
        <div class="mt-20" style="width: 33%">打款金额：￥{{ dataInfo.minAmount }}~{{ dataInfo.maxAmount }}</div>
        <div class="mt-20" style="width: 33%">提现时间：24小时内</div>
        <div class="mt-20" style="width: 33%">操作人：{{ dataInfo.handleUser }}</div>
      </div>
    </div>
    <div class="round-14 flex-col bgfff p-20 flex-1">
      <a-form label-align="right" layout="inline" auto-label-width :model="listParams" size="small" class="form my-10">
        <a-form-item field="status" hide-label>
          <a-select
            v-model="listParams.status"
            placeholder="请选择打款状态"
            class="w-40n"
            @change="changeCurrent(1)"
            allow-clear
          >
            <a-option value="" label="全部"></a-option>
            <a-option :value="20" label="签约失败"></a-option>
            <a-option :value="3" label="打款中"></a-option>
            <a-option :value="4" label="打款成功"></a-option>
            <a-option :value="40" label="打款失败"></a-option>
            <a-option :value="41" label="已退款"></a-option>
          </a-select>
        </a-form-item>
        <a-form-item field="withdrawalStartTime" hide-label>
          <MsDate
            v-model:start="listParams.withdrawalStartTime"
            v-model:end="listParams.withdrawalEndTime"
            @dateChange="changeCurrent(1)"
          />
        </a-form-item>
        <a-form-item field="keyword" hide-label>
          <a-input
            v-model="listParams.keyword"
            placeholder="输入用户邀请码/手机号"
            @press-enter="changeCurrent(1)"
          ></a-input>
        </a-form-item>
        <a-form-item hide-label>
          <a-space>
            <a-button type="primary" size="small" @click="changeCurrent(1)">
              <template #icon>
                <icon-search />
              </template>
              <template #default>查询</template>
            </a-button>
            <a-button size="small" @click="onResetSearch">
              <template #icon>
                <icon-sync />
              </template>
              <template #default>重置</template>
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
      <div class="w-full flex-1 overflower-hidden m-relative">
        <div class="m-absolute t-0 b-0 r-0 l-0 flex" style="background: red">
          <GiTable
            row-key="withdrawalId"
            id="financeTaskDetail"
            ref="tt"
            v-model:columns="columns"
            :loading="loading"
            :data="tableData"
            :row-selection="{ type: 'checkbox', showCheckedAll: true }"
            v-model:selectedKeys="selectedKeys"
            :scroll="{ x: '100%', y: '100%', minWidth: 1000 }"
            :pagination="pagination"
            @refresh="getTableData"
            :hide="true"
          >
            <template #custom-extra>
              <a-space>
                <a-button type="primary" size="small" @click="onAdd">
                  <template #icon><icon-plus /></template>
                  <span>新建任务</span>
                </a-button>
                <template v-if="btnShow">
                  <a-button type="primary" size="small" status="warning" @click="onBatchRemoveFailTask(false)">
                    <template #icon><icon-delete /></template>
                    <span>批量移除打款失败的任务</span>
                  </a-button>
                  <a-button type="primary" size="small" status="danger" @click="onBatchRefundFailTask(false)">
                    <template #icon><icon-delete /></template>
                    <span>批量退款打款失败的任务</span>
                  </a-button>
                </template>
                <!-- <a-button type="primary" size="small" status="warning" @click="onBatchRemoveFailTask(false)">
                  <template #icon><icon-delete /></template>
                  <span>批量退款打款失败的任务</span>
                </a-button> -->
                <a-button
                  type="primary"
                  size="small"
                  status="warning"
                  :loading="statusLoading"
                  @click="onUpdateTaskStatus"
                >
                  <template #icon><icon-sync /></template>
                  <span>同步任务状态</span>
                </a-button>
              </a-space>
            </template>
            <template #user="{ record }">
              <div class="flex-col">
                <span>邀请码：{{ record.inviteCode }}</span>
                <span>手机号：{{ record.mobile }}</span>
              </div>
            </template>
            <template #info="{ record }">
              <div class="flex-col">
                <span>姓名：{{ record.withdrawalAccountInfo.withdrawalName }}</span>
                <span>账号：{{ record.withdrawalAccountInfo.withdrawalAccount }}</span>
              </div>
            </template>
            <template #status="{ record }">
              <div class="flex-col flex-a-c">
                <a-tag
                  :color="
                    record.status == 1
                      ? '#165dff'
                      : record.status == 2
                      ? '#7bc616'
                      : record.status == 3
                      ? '#165dff'
                      : record.status == 4
                      ? '#00b42a'
                      : record.status == 20
                      ? '#f53f3f'
                      : record.status == 40
                      ? '#f53f3f'
                      : record.status == 41
                      ? '#b71de8'
                      : '#86909c'
                  "
                  >{{
                    record.status == 1
                      ? '签约中'
                      : record.status == 2
                      ? '签约完成'
                      : record.status == 3
                      ? '打款中'
                      : record.status == 4
                      ? '打款成功'
                      : record.status == 20
                      ? '签约失败'
                      : record.status == 40
                      ? '打款失败'
                      : record.status == 41
                      ? '退款成功'
                      : '--'
                  }}</a-tag
                >
                <span class="text-size-12 mt-4" style="color: red" v-if="record?.relRes">
                  {{ record.relRes }}
                </span>
              </div>
            </template>
            <template #action="{ record }">
              <template v-if="record.status == 40">
                <a-button type="text" size="small" @click="onOpenTipModal(record.withdrawalId, record)">
                  修改失败提示
                </a-button>
                <a-button type="text" size="small" @click="onBatchRefundFailTask(record.withdrawalId)"> 退款 </a-button>
                <a-button type="text" size="small" @click="onBatchRemoveFailTask(record.withdrawalId)"> 移除 </a-button>
              </template>
              <span v-else>--</span>
            </template>
          </GiTable>
        </div>
      </div>
    </div>
    <a-modal v-model:visible="visible" title="修改打款失败提示语" @before-ok="onOk">
      <a-form :model="failParam">
        <a-form-item hide-label>
          <a-textarea
            placeholder="请输入"
            :auto-size="{
              minRows: 3
            }"
            v-model="failParam.payResponse"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { Message, Modal } from '@arco-design/web-vue'
import { usePagination } from '@/hooks'
import {
  userPayTaskDetail,
  getTaskUserList,
  batchRemoveFailTask,
  batchRefundFailTask,
  editTaskPayResponse,
  userPayTaskUpdateTaskStatus
} from '@/apis'
import { reAssign, deleteEmpty } from '@/utils/common'
import { useTabsStore } from '@/store'
import $bus from '@/utils/bus'
defineOptions({ name: 'financeTaskDetail' })
const route = useRoute()
const router = useRouter()
const tt = ref()
const columns = ref([
  {
    title: '提现用户',
    width: 150,
    slotName: 'user'
  },
  {
    title: '提现金额',
    width: 120,
    dataIndex: 'withdrawalAmount'
  },
  {
    title: '用户状态',
    width: 120,
    align: 'center',
    slotName: 'status'
  },
  {
    title: '提现时间',
    width: 180,
    dataIndex: 'withdrawalTime'
  },
  {
    title: '提现凭证',
    width: 150,
    dataIndex: 'withdrawalNo'
  },
  {
    title: '提现帐号',
    width: 330,
    slotName: 'info'
  },
  {
    title: '操作',
    width: 160,
    align: 'center',
    fixed: 'right',
    slotName: 'action'
  }
])

const loading = ref(false)
const statusLoading = ref(false)
const tableData = ref([])
const visible = ref(false)
const btnShow = computed(() => {
  return tableData.value.every((item) => item.status == 40)
})
const dataInfo = reactive({
  failAmount: 0,
  failCount: 0,
  handleUser: '',
  maxAmount: '',
  minAmount: '',
  name: '',
  payAccountName: '',
  payType: '1',
  payTypeName: '',
  signFailCount: 0,
  signSuccessCount: 0,
  status: '1',
  submitStartAt: '',
  submitStartEnd: '',
  successAmount: 0,
  successCount: 0,
  totalAmount: 0,
  totalCount: 0
})
const selectedKeys = ref([])
const failParam = reactive({
  withdrawalId: undefined,
  payResponse: undefined
})
const listParams = reactive({
  keyword: undefined,
  status: undefined,
  withdrawalStartTime: undefined,
  withdrawalEndTime: undefined,
  page: 1,
  pageSize: 15,
  taskId: undefined
})
const { pagination, setTotal } = usePagination(() => getTableData(), { defaultPageSize: listParams.pageSize })

const getDetail = async () => {
  const res = await userPayTaskDetail({ taskId: route.query.id })
  columns.value[5].title = `提现帐号（${res.data.payTypeName}）`
  console.log(res.data.payTypeName)
  reAssign(dataInfo, res.data)
  if (res.data.name) useTabsStore().changeTagTitle(`【${res.data.name}】详情`)
}

// 获取列表数据
const getTableData = async () => {
  try {
    loading.value = true
    listParams.page = pagination.current
    listParams.pageSize = pagination.pageSize
    if (!listParams.taskId) listParams.taskId = route.query.id
    getDetail()
    const res = await getTaskUserList(deleteEmpty(listParams))
    tableData.value = res.data.list.map((item) => {
      const str1 = item?.signResponse?.msg ? item.signResponse.msg + '\n' : ''
      const str2 = item?.signResponse?.subMsg ? item.signResponse.subMsg : ''
      const relRes = item.payResponse || str1 + str2
      return {
        relRes,
        ...item
      }
    })
    setTotal(res?.data?.meta?.pagination?.total || 0)
  } finally {
    loading.value = false
  }
}

// 表格页码改变
const changeCurrent = (e) => {
  pagination.current = listParams.page = e
  getTableData()
}

// 打开提示语弹窗
const onOpenTipModal = (e, record) => {
  failParam.withdrawalId = e
  failParam.payResponse = record.relRes
  visible.value = true
}

// 重置筛选查询
const onResetSearch = () => {
  listParams.keyword = listParams.status = listParams.withdrawalStartTime = listParams.withdrawalEndTime = undefined
  changeCurrent(1)
}

// 点击新建
const onAdd = () => {
  //   $bus.emit('financeTask')
  router.push({
    name: 'payment'
  })
}

// 点击确认添加/编辑
const onOk = async () => {
  if (!failParam.payResponse) {
    Message.warning('请填写提示语！')
    return false
  }
  await editTaskPayResponse(failParam)
  Message.success('修改成功')
  getTableData()
  return true
}

// 删除用户
const onBatchRemoveFailTask = (withdrawalId) => {
  if (selectedKeys.value.length === 0 && !withdrawalId) return Message.warning('请选择要删除的用户！')
  Modal.warning({
    title: '批量移除',
    content: '是否确认移除选中的打款失败用户？',
    hideCancel: false,
    onOk: async () => {
      try {
        loading.value = true
        await batchRemoveFailTask({
          taskId: route.query.id,
          withdrawalId: withdrawalId ? [withdrawalId] : selectedKeys.value
        })
        Message.success('删除成功！')
        selectedKeys.value = []
        changeCurrent(1)
      } finally {
        loading.value = false
      }
    }
  })
}
// 更新状态
const onUpdateTaskStatus = async () => {
  try {
    statusLoading.value = true
    await userPayTaskUpdateTaskStatus({
      taskId: route.query.id
    })
    Message.success('操作成功！')
    changeCurrent(1)
  } finally {
    statusLoading.value = false
  }
}
// 退款
const onBatchRefundFailTask = (withdrawalId) => {
  if (selectedKeys.value.length === 0 && !withdrawalId) return Message.warning('请选择要退款的的用户！')
  Modal.warning({
    title: '批量退款',
    content: '是否确认给选中的打款失败用户退款？',
    hideCancel: false,
    onOk: async () => {
      try {
        loading.value = true
        await batchRefundFailTask({
          taskId: route.query.id,
          withdrawalId: withdrawalId ? [withdrawalId] : selectedKeys.value
        })
        Message.success('操作成功！')
        selectedKeys.value = []
        changeCurrent(1)
      } finally {
        loading.value = false
      }
    }
  })
}

onMounted(() => {
  if (route.query.status) listParams.status = Number(route.query.status)
  tt.value?.resetcolumns(true)
  changeCurrent(1)
  $bus.on('financeTaskList', () => {
    changeCurrent(1)
  })
})

onUnmounted(() => {
  $bus.off('financeTaskList')
})
</script>

<style lang="scss" scoped>
.table-page {
  background: transparent;
}
</style>
